package com.qf.interceptor;

import com.qf.bean.User;
import com.qf.constant.SSMConstant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenInterceptor implements HandlerInterceptor{
    //拦截器的前处理，请求到达前端控制器之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse,
                             Object handler) throws Exception {
        //1.获得session对象
        HttpSession session = httpServletRequest.getSession();
        //2.从session域中获取用户信息
        User user = (User) session.getAttribute(SSMConstant.USER);
        //3.判断用户是否登录
        if(user != null){
            return true;
            //->登录  放行
        }else {
            //->未登录 重定向到登录页面 拦截
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/user/login");
            return false;
        }

    }
    //渲染视图之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse, Object handler,
                           ModelAndView modelAndView) throws Exception {
        //给modelAndView添加或修改数据
        System.out.println("渲染视图之前。。。");
    }
    //响应数据之前
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    //  粗粒度查看访问量
        //记录日志
        System.out.println("响应数据之前。。。");
    }
}
